package com.ergwang.filter;

import com.ergwang.Model.Admin;
import com.ergwang.Model.Result;
import com.google.gson.Gson;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author：ergwang
 * @Date: 2020/6/2
 * @Time: 10:31
 */
@WebFilter("/api/mall/*")
public class MallFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        // 将*改为了页面系统所在的域
        response.setHeader("Access-Control-Allow-Origin","http://localhost:8085");
        response.setHeader("Access-Control-Allow-Methods","POST,GET,OPTIONS,PUT,DELETE");
        response.setHeader("Access-Control-Allow-Headers","x-requested-with,Authorization,Content-Type");
        response.setHeader("Access-Control-Allow-Credentials","true");
        String requestURI = request.getRequestURI();
        // 1,需要拦截那些请求
        // 2，针对需要拦截的，判断有无session数据
        // 3，如果没有，就拦截
//        if (auth(requestURI)){
//            Admin admin = (Admin) request.getSession().getAttribute("admin");
//            if (admin == null){
//                response.getWriter().println(new Gson().toJson(Result.error("当前接口仅登陆后可以访问！")));
//            }
//        }
        chain.doFilter(request, response);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
